package com.cts.tmall.app.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.EnumerationUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.stream.Collectors;

/**
 * 日志拦截器
 *
 * @author leibing.song
 * @since 2020-07-29
 */
@Slf4j
@Component
public class LoggerInterceptor implements HandlerInterceptor {

  public static final String TRACE_ID_KEY = "trace_id";
  public static final String START_TIME_KEY = "start_time";

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (DispatcherType.ASYNC.equals(request.getDispatcherType())) {
      MDC.put(TRACE_ID_KEY, request.getAttribute(TRACE_ID_KEY).toString());
    } else {
      String traceId = RandomStringUtils.randomNumeric(50);
      request.getSession().setAttribute(TRACE_ID_KEY, traceId);
      request.getSession().setAttribute(START_TIME_KEY, System.currentTimeMillis());
      MDC.put(TRACE_ID_KEY, traceId);

      String requestBody = StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset());
      String requestParameter = EnumerationUtils.toList(request.getParameterNames()).stream().map(name -> name + " : " + request.getParameter(name)).collect(Collectors.joining("\n"));
      String requestHeader = EnumerationUtils.toList(request.getHeaderNames()).stream().map(name -> name + " : " + request.getHeader(name)).collect(Collectors.joining("\n"));

      log.info("请求地址：{}", request.getRequestURL());
      log.info("请求头:{}", requestHeader);
      log.info("请求参数：{}", requestParameter);
      log.info("请求体：{}", requestBody);
    }
    return Boolean.TRUE;
  }
}
